﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using JX.Infrastructure;
using JX.Infrastructure.AliyunOSS;
using JX.Infrastructure.Common;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using UEditor.Core;
using UEditor.Core.Handlers;

namespace JXWebSite.Controllers
{
	/// <summary>
	/// 编辑器控制器
	/// </summary>
    public class UEditorController : Controller
    {
        private readonly UEditorService _ueditorService;
		/// <summary>
		/// 依赖注入
		/// </summary>
		/// <param name="ueditorService"></param>
        public UEditorController(UEditorService ueditorService)
        {
            this._ueditorService = ueditorService;
        }

		/// <summary>
		/// 上传
		/// </summary>
		/// <returns></returns>
        [HttpGet, HttpPost]
        public ContentResult Upload()
        {
			//检查是否开启上传权限
			var uploadConfig = ConfigHelper.Get<UploadFilesConfig>();
			if (!uploadConfig.EnableUploadFiles)
			{
				UEditorResult Result = new UEditorResult();
				Result.State = "没有开启上传权限";
				Result.Error = "没有开启上传权限";
				string resultJson = JsonConvert.SerializeObject(Result, new JsonSerializerSettings
				{
					NullValueHandling = NullValueHandling.Ignore
				});
				return Content(resultJson, "text/plain");
			}
			//处理上传程序
			var response = _ueditorService.UploadAndGetResponse(HttpContext);

			//如果是得到上传配置，则直接返回
			var action = HttpContext.Request.Query["action"];
			switch (action)
			{
				case "listimage":
				case "listfile":
					#region 从OSS中得到文件列表进行显示
					string prefix = "image";
					if(action == "listfile")
					{
						prefix = "file";
					}
					var ossListKey = AliyunOssHelper.GetListObject(prefix);
					if(ossListKey != null && ossListKey.Count > 0)
					{
						var ueditorResultOSS = new UEditorResult
						{
							State = "SUCCESS",
							List = ossListKey.Select(x => new UEditorFileList { Url = x }),
							Start = 0,
							Size = ossListKey.Count,
							Total = ossListKey.Count
						};
						string resultJson = JsonConvert.SerializeObject(ueditorResultOSS, new JsonSerializerSettings
						{
							NullValueHandling = NullValueHandling.Ignore
						});
						response = new UEditorResponse(response.ContentType, resultJson);
					}
					#endregion
					break;
				case "uploadimage":
				case "uploadscrawl":
				case "uploadvideo":
				case "uploadfile":
					#region 处理上传到OSS
					if (ConfigHelper.GetAppSettingSection<AliyunOssConfig>().EnableOSS)
					{
						//检查是否有上传回调函数
						string ueResultJson = response.Result;
						string jsonpCallback = HttpContext.Request.Query["callback"];
						if (!jsonpCallback.IsNullOrWhiteSpace())
						{
							ueResultJson = response.Result.Replace(jsonpCallback + "(", string.Empty).TrimEnd(';').TrimEnd(')');
						}
						//反序列化UEditorResult对像
						var ueditorResult = JsonConvert.DeserializeObject<UEditorResult>(ueResultJson, new JsonSerializerSettings
						{
							NullValueHandling = NullValueHandling.Ignore
						});
						//上传成功则把文件再上传到OSS中，并删除本地文件
						if (ueditorResult.State == "SUCCESS")
						{
							string filePath = FileHelper.MapPath(FileHelper.WebRootPath + FileHelper.DirectorySeparatorChar + ueditorResult.Url);
							var resultOSS = AliyunOssHelper.UploadToOSS(filePath);
							if (resultOSS.Status == 1)
							{
								System.IO.File.Delete(filePath);
								ueditorResult.Url = resultOSS.Url;
							}
							string resultJson = JsonConvert.SerializeObject(ueditorResult, new JsonSerializerSettings
							{
								NullValueHandling = NullValueHandling.Ignore
							});
							if (!jsonpCallback.IsNullOrWhiteSpace())
							{
								resultJson = string.Format("{0}({1});", jsonpCallback, resultJson);
							}
							response = new UEditorResponse(response.ContentType, resultJson);
						}
					}
					#endregion
					break;
				default:
					break;
			}
			return Content(response.Result, response.ContentType);
        }
    }
}